import Cookies from 'js-cookie';
import { Base64 } from "js-base64"
import {domain, rootDomain, serverHost} from "@/js/config";
import axios from 'axios'


// 判空
export const isEmpty = (val) => {
    return val === undefined || val === null || val === 0 || val === false || val === '' || val.constructor === Array && val.length === 0 || val.constructor === Object && Object.keys(val).length === 0;
}


// 解码
export const transformBase64 = (base64String) => {
    return Base64.decode(base64String)
}
  
// 获取浏览器
export const getBrowser = () => {
    let UserAgent = navigator.userAgent.toLowerCase();
    let browserInfo = {};
    let browserArray = {
        Chrome: UserAgent.indexOf('chrome') > -1 && UserAgent.indexOf('safari') > -1, // Chrome浏览器
        Firefox: UserAgent.indexOf('firefox') > -1, // 火狐浏览器
        Opera: UserAgent.indexOf('opera') > -1, // Opera浏览器
        Safari: UserAgent.indexOf('safari') > -1 && UserAgent.indexOf('chrome') === -1, // safari浏览器
        Edge: UserAgent.indexOf('edg') > -1, // Edge浏览器
        QQBrowser: /qqbrowser/.test(UserAgent), // qq浏览器
        WeixinBrowser: /MicroMessenger/i.test(UserAgent) // 微信浏览器
    };

    for (let i in browserArray) {
        if (browserArray[i]) {
            let versions = '';
            if (i === 'IE') {
                versions = UserAgent.match(/(msie\s|trident.*rv:)([\w.]+)/)[2];
            } else if (i === 'Chrome') {
                for (let mt in navigator.mimeTypes) {
                    //检测是否是360浏览器(测试只有pc端的360才起作用)
                    if (navigator.mimeTypes[mt]['type'] === 'application/360softmgrplugin') {
                        i = '360';
                    }
                }
                versions = UserAgent.match(/chrome\/([\d.]+)/)[1];
            } else if (i === 'Firefox') {
                versions = UserAgent.match(/firefox\/([\d.]+)/)[1];
            } else if (i === 'Opera') {
                versions = UserAgent.match(/opera\/([\d.]+)/)[1];
            } else if (i === 'Safari') {
                versions = UserAgent.match(/version\/([\d.]+)/)[1];
            } else if (i === 'Edge') {
                versions = UserAgent.match(/edg\/([\d.]+)/)[1];
            } else if (i === 'QQBrowser') {
                versions = UserAgent.match(/qqbrowser\/([\d.]+)/)[1];
            }
            browserInfo.type = i;
            browserInfo.versions = parseInt(versions);
        }
    }
    return browserInfo;
}
// 设置token过期时间
export const setInstallCookie = (thisKey) => {
    Cookies.set("smart-id-token", thisKey, {expires: 730, domain: rootDomain});
    Cookies.set("logged-on", 'Y', {expires: 3650});
}

export const getCommonHeader = () => {
    let isInstallPlugin = Cookies.get("installed");
    let token = Cookies.get('smart-id-token');
    let appVersion = Cookies.get('app_version');
    let appType = Cookies.get('app_type');
    let result = {
        'origin-page': 'web',
        'Content-Type': 'application/json;charset=utf-8',
        'Authorization': "Bearer " + token,
    };
    if(isInstallPlugin && isInstallPlugin !== 'false' && isInstallPlugin !== false){
        result['user-id'] = isInstallPlugin;
        result['cb-user-id'] = isInstallPlugin;
    }
    if (appVersion){
        result['cb-app-version-num'] = getVersionNumber(appVersion);
    }
    if (appType){
        result['cb-app-type'] = appType;
    }
    return result;
}

export const clickLog = (clickFlag, data) => {
    let result = {};
    result['clickFlag'] = clickFlag;
    result['actionUrl'] = window.location.href;
    let isInstallPlugin = Cookies.get("installed");
    let visitId = Cookies.get("c_vid");
    let config = {
        headers: getCommonHeader(),
    };
    if(isInstallPlugin && isInstallPlugin !== 'false' && isInstallPlugin !== false){
        result['userId'] = isInstallPlugin;
    }
    if(visitId && visitId !== false && visitId !== 'false'){
        result['cbVisitorId'] = visitId
    }
    result = Object.assign(result, data);
    axios.post(serverHost + '/v1/commonLog/action/click',result, config).then();
}
/**
 * 记录卸载Log
 */
export const uninstallLog = () => {
    let uninstallResult = {};
    let browser = getBrowser()
    let userId = Cookies.get("installed")
    if (userId !== undefined){
        uninstallResult["userId"] = Cookies.get("installed");
        uninstallResult["cbVisitorId"]= Cookies.get('c_vid');
        uninstallResult["appType"] = Cookies.get('app_type');
        uninstallResult["appVersion"] = Cookies.get('app_version');
        uninstallResult["userBrowser"] = browser.type + " " + browser.versions;
        uninstallResult["userAgent"] = navigator.userAgent;
        uninstallResult["flag"] = "uninstall"
        axios.post(serverHost + '/v1/commonLog/action/appAction', uninstallResult).then();
    }
}

export const deleteCookie = () => {
    Cookies.remove("installed", {path: '/', domain: rootDomain})
    Cookies.remove("installed", {path: '/', domain: domain})
    Cookies.remove('app_type', {path: '/', domain: rootDomain})
    Cookies.remove('app_type', {path: '/', domain: domain})
    Cookies.remove('app_version', {path: '/', domain: rootDomain})
    Cookies.remove('app_version', {path: '/', domain: domain})
}

/**
 * 获取last used时间字符
 * @param originTime
 * @returns {null}
 */
export const getLastUsedTimeDifference = (originTime) => {
    let nowTime = parseInt(new Date().getTime() / 1000);
    let result = '';
    if (nowTime > originTime && (nowTime - 86400) < originTime){
        let timeDifference = nowTime - originTime;
        let hours = parseInt(timeDifference / 3600);
        if (hours === 0){
            let minutes = Math.ceil(timeDifference / 60);
            if (minutes === 1){
                result = minutes.toString() + ' min';
            }else if (minutes === 60){
                result = '1 hour';
            }else {
                result = minutes.toString() + ' mins';
            }
        } else if (hours === 1){
            result = hours.toString() + ' hour';
        } else {
            result = hours.toString() + ' hours';
        }
    }
    return result;
}

export const getVersionNumber = (appVersion) => {
    let version = appVersion;
    if (isEmpty(version) || typeof version !== 'string') {
        return 0;
    }
    let versionList = version.split('.');
    if (versionList.length !== 3) {
        return 0;
    }
    let versionNumList = [];
    for (let i in versionList) {
        let tempNum = parseInt(versionList[i]);
        if (isNaN(tempNum) || tempNum < 0 || tempNum >= 100) {
            return 0;
        } else {
            versionNumList.push(tempNum);
        }
    }
    return versionNumList[0] * 10000 + versionNumList[1] * 100 + versionNumList[2];
}

export const sendVisitLog = (to) => {
    let data = {};
    data['url'] = serverHost + to.fullPath;
}

export const allowCountry = () => {
    let country = Cookies.get("country")
    let countryList = ['us', 'gb', 'ca', 'au'];
    if (country === "" || country === undefined) {
        return false;
    }
    return countryList.indexOf(country.toLowerCase()) !== -1;
}

// export const transformBase64 = (base64String) => {
//   return Base64.decode(base64String)
// }